<template>
  <div class="app-container">
    <el-tabs style="margin-top:15px; min-height: 600px;" type="border-card">
      <el-tab-pane key="1" :label="$t('basic.ServerSetting')">
        <keep-alive>
          <el-form ref="dataForm" :rules="rules" label-position="left" label-width="120px" style="width: 600px; margin-left:50px;">
            <el-form-item v-for="item in emailShift" :key="item.varName" :label="item.varDescription" :prop="item.varName">
              <el-input v-model="item.varValue" :type="typeOptions[item.varType]" />
            </el-form-item>
          </el-form>
        </keep-alive>
      </el-tab-pane>
      <el-tab-pane key="2" :label="$t('basic.CompanySetting')">
        <keep-alive>
          <el-form ref="dataForm" :rules="rules" label-position="left" label-width="120px" style="width: 600px; margin-left:50px;">
            <el-form-item v-for="item in companyShift" :key="item.varName" :label="item.varDescription" :prop="item.varName">
              <el-input v-model="item.varValue" clearable />
            </el-form-item>
          </el-form>
        </keep-alive>
      </el-tab-pane>
    </el-tabs>
    <div slot="footer" style="float:right; margin-right:50px;margin-top:10px" class="dialog-footer">
      <el-button @click="handleFilter">
        {{ $t('common.load') }}
      </el-button>
      <el-button type="primary" @click="dialogStatus==='create'?createData():updateData()">
        {{ $t('common.save') }}
      </el-button>
    </div>
  </div>
</template>

<script>
import { getBasicInfo, updateBasicInfo } from '@/api/basic'
import waves from '@/directive/waves' // waves directive
import { parseTime } from '@/utils'
import i18n from '@/lang'

export default {
  name: 'BasicInfo',
  components: {
  },
  directives: { waves },
  filters: {
    statusFilter(status) {
      const statusMap = {
        published: 'success',
        draft: 'info',
        deleted: 'danger'
      }
      return statusMap[status]
    }
  },
  data() {
    return {
      editRight: true,
      tableKey: 0,
      activeName: '1',
      list: [],
      emailShift: [],
      companyShift: [],
      total: 0,
      listLoading: true,
      listQuery: {
        page: 1,
        limit: 20,
        state: 0,
        varDescription: '',
        varShift: 0,
        language: this.$store.getters.language,
        startTime: parseTime(Date.now(), '{y}-{m}-{d} 00:00:00'),
        endTime: '',
        sort: '+due_date'
      },
      typeOptions: ['', 'email', 'number', 'password'],
      showReviewer: false,
      temp: {
        bomId: 0,
        bomCode: '',
        bomName: '',
        lineName: '',
        processId: 0
      },
      dialogFormVisible: false,
      dialogStatus: 'update',
      textMap: {
        update: i18n.t('common.edit'),
        create: i18n.t('common.creatNew')
      },
      dialogPvVisible: false,
      pvData: [],
      rules: {
      },
      downloadLoading: false,
      searchLoading: {
        company: false,
        manager: false
      },
      searchDialogStatus: '',
      searchDialogFormVisible: {
        company: false,
        manager: false
      }
    }
  },
  created() {
    this.getList()
    this.editRight = (this.$store.getters.roles === 'admin' || this.$store.getters.roles === 'administrator')
  },
  methods: {
    formatDateTime(date) {
      return date.substring(0, 10)
    },
    // 获取清单
    getList() {
      this.listLoading = true
      getBasicInfo(this.listQuery).then(response => {
        this.list = response.data.basicInfos
        this.emailShift = []
        this.companyShift = []
        this.list.forEach(val => {
          switch (val.varShift) {
            case 1:
              this.emailShift.push(val)
              break
            case 2:
              this.companyShift.push(val)
              break
          }
        })
        this.total = response.data.total
        this.listLoading = false
      })
    },
    // 查看线体设备
    handleCheckLine(row) {
      const ret = Object.assign({}, row) // copy obj
      this.$router.push({ path: '/equipment/stationDef', query: { lineId: ret.lineId }})
    },
    // 查看错误信息
    handleCheck(row) {
      const ret = Object.assign({}, row) // copy obj
      if (ret.errMsg === null | '') {
        return
      }
      this.$msgbox({
        message: ret.errMsg,
        type: 'error'
      })
    },
    // 点击搜索时获取清单
    handleFilter() {
      this.listQuery.page = 1
      this.getList()
    },
    // 排序时调用
    sortChange(data) {
      const { prop, order } = data
      if (prop === 'startDate') {
        this.sortByCreatTime(order)
      } else if (prop === 'dueDate') {
        this.sortBydueDate(order)
      } else if (prop === 'priority') {
        this.sortByPriority(order)
      }
    },
    // 根据创建时间排序
    sortByCreatTime(order) {
      if (order === 'ascending') {
        this.listQuery.sort = '+start_date'
      } else {
        this.listQuery.sort = '-start_date'
      }
      this.handleFilter()
    },
    // 根据交期排序
    sortBydueDate(order) {
      if (order === 'ascending') {
        this.listQuery.sort = '+due_date'
      } else {
        this.listQuery.sort = '-due_date'
      }
      this.handleFilter()
    },
    // 根据优先级
    sortByPriority(order) {
      if (order === 'ascending') {
        this.listQuery.sort = '+priority'
      } else {
        this.listQuery.sort = '-priority'
      }
      this.handleFilter()
    },
    // 点击编辑按钮
    handleUpdate(row) {
      this.temp = Object.assign({}, row) // copy obj
      this.dialogStatus = 'update'
      this.$nextTick(() => {
        this.$refs['dataForm'].clearValidate()
      })
    },
    // 更新数据到数据库
    updateData() {
      this.$confirm(i18n.t('msg.CONFIRM_SAVE_CHANGE'), i18n.t('common.warn'), {
        confirmButtonText: i18n.t('common.confirm'),
        cancelButtonText: i18n.t('common.cancel'),
        type: 'warning'
      })
        .then(async() => {
          updateBasicInfo(this.list).then(() => {
            this.$notify({
              title: this.$i18n.t('common.tip'),
              message: i18n.t('msg.UPDATE_SUCCESS'),
              type: 'success',
              duration: 2000
            })
          })
        })
        .catch(err => { console.error(err) })
    },
    // 下载所有导出信息
    handleDownload() {
      this.downloadLoading = true
      import('@/vendor/Export2Excel').then(excel => {
        const tHeader = [i18n.t('bom.bomName'),
          i18n.t('bom.bomName')]
        const filterVal = ['bomName', 'bomName']
        const data = this.formatJson(filterVal)
        excel.export_json_to_excel({
          header: tHeader,
          data,
          filename: '物料清单'
        })
        this.downloadLoading = false
      })
    },
    // 过滤相关信息
    formatJson(filterVal) {
      return this.list.map(v => filterVal.map(j => {
        if (j === 'timestamp') {
          return parseTime(v[j])
        } else {
          return v[j]
        }
      }))
    }
  }
}
</script>
<style lang="scss" scoped>
.dashboard-editor-container {
  padding: 32px;
  height: 800px;
  background-color: white;
  position: relative;

  .github-corner {
    position: absolute;
    top: 0px;
    border: 0;
    right: 0;
  }

  .chart-wrapper {
    background: #fff;
    padding: 16px 16px x0;
    //margin-bottom: 32px;
  }
}

@media (max-width:1024px) {
  .chart-wrapper {
    padding: 8px;
  }
}
</style>
